﻿using System;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;

using Our.Umbraco.UniversalMediaPicker.Providers.TwitPic.Model;
using TheOutfield.UmbExt.UniversalMediaPicker;

namespace Our.Umbraco.UniversalMediaPicker.Providers.TwitPic
{
	public static class TwitPicExtensions
	{
		public static XPathNavigator ToXPathNavigator(this XmlReader reader)
		{
			var xd = new XmlDocument();
			xd.Load(reader);
			return xd.CreateNavigator();
		}

		public static TwitPicImage ToTwitPicImage(this XmlReader reader)
		{
			var serializer = new XmlSerializer(typeof(TwitPicImage));

			if (serializer.CanDeserialize(reader))
			{
				return (TwitPicImage)serializer.Deserialize(reader);
			}

			return null;
		}

		public static TwitPicUser ToTwitPicUser(this XmlReader reader)
		{
			var serializer = new XmlSerializer(typeof(TwitPicUser));

			if (serializer.CanDeserialize(reader))
			{
				return (TwitPicUser)serializer.Deserialize(reader);
			}

			return null;
		}

		public static MediaItem ToMediaItem(this TwitPicImage image)
		{
			if (image != null)
			{
				string title = image.Timestamp;
				if ( !string.IsNullOrEmpty(image.Message))
				{
					title = image.Message.Length > 35 ? image.Message.Substring(0, 32) + "..." : image.Message;
				}

				var mediaItem = new MediaItem
				{
					Id = image.ShortId,
					Title = title,
					PreviewImageUrl = image.ImageMiniUrl,
					HasChildren = false,
					Selectable = true
				};

				mediaItem.MetaData.Add("Message", image.Message);
				mediaItem.MetaData.Add("Height", image.Height.ToString());
				mediaItem.MetaData.Add("Width", image.Width.ToString());
				mediaItem.MetaData.Add("Type", image.Type);
				mediaItem.MetaData.Add("Views", image.Views.ToString());

				return mediaItem;
			}

			return null;
		}
	}
}
